﻿using System;
using System.Web;
using System.Globalization;

using Fuse8.DomainFramework.Domain;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.Common.Exceptions;
using Fuse8.DomainFramework.Common;

namespace Fuse8.DomainFramework.DataAccess
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class UnitOfWorkScope<TEntity> : IDisposable
        where TEntity : class, IEntityObject, new()
    {
        #region Fields

        private static readonly string _typeParameter = new TEntity().TypeParameter;

        private HttpContextBase _currentContext;

        private bool _isDisposed = false;

        #endregion        

        /// <summary>
        /// 
        /// </summary>
        public HttpContextBase CurrentHttpContext
        {
            get
            {
                return _currentContext != null ?
                    _currentContext :
                    HttpContext.Current != null ?
                        new HttpContextWrapper(HttpContext.Current) as HttpContextBase :
                        DummyHttpContext.GetInstance();
            }
            set
            {
                _currentContext = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected virtual string FactoryKeyFormat
        {
            get
            {
                return "HttpContextUnitOfWorkScope_{0}";
            }
        }

        #region Constructor

        /// <summary>
        /// 
        /// </summary>
        public UnitOfWorkScope()
        {
            string factoryKey = GenerateFactoryKey();
            var existingScope = CurrentHttpContext.Items[factoryKey] as UnitOfWorkScope<TEntity>;

            if (existingScope == null)
            {
                if (UnitOfWorkController<TEntity>.GetCurrentUnitOfWork() == null)
                {
                    throw new UnitOfWorkNotDefinedException();
                }

                CurrentHttpContext.Items[factoryKey] = this;
            }
            else
            {
                _isDisposed = true;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual string GenerateFactoryKey()
        {
            return string.Format(CultureInfo.InvariantCulture, FactoryKeyFormat, _typeParameter);
        }

        #endregion

        #region IDisposable Members

        /// <summary>
        /// 
        /// </summary>
        ~UnitOfWorkScope()
        {
            Dispose(false);
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                {
                    UnitOfWorkController<TEntity>.CallCloseToUnitOfWork();
                }

                CurrentHttpContext.Items.Remove(GenerateFactoryKey());
            }

            _isDisposed = true;
        }
        
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
